"""
连接MySQL服务器，执行update操作
"""
import pymysql

from utils import create_connection


class Course:

    def __init__(self, id=None, name=None, credit=None):
        self.id = id
        self.name = name
        self.credit = credit

    def __str__(self):
        return f'编号: {self.id}\n名称: {self.name}\n学分: {self.credit}'


# 第一步：创建连接对象
conn = create_connection(database='school')
try:
    # 第二步：通过连接对象获取游标对象
    with conn.cursor(pymysql.cursors.DictCursor) as cursor:
        # 第三步：通过游标对象向数据库服务器发出SQL语句
        cursor.execute('select cou_id as id, cou_name as name, cou_credit as credit from tb_course')
        # 第四步：获取查询结果（通过游标抓取数据）
        # fetchone() ----> 抓取一条数据 ---> 元组
        # fetchall() ----> 抓取所有数据 ---> 嵌套元组
        # fetchmany(n) ----> 抓取指定数量的数据 ---> 嵌套元组
        # print(cursor.fetchone())
        row_dict = cursor.fetchone()
        while row_dict:
            course = Course(**row_dict)
            # print(course.name, course.credit)
            print(course)
            print('-' * 20)
            row_dict = cursor.fetchone()
except pymysql.MySQLError as err:
    print(err)
finally:
    # 第五步：关闭连接释放资源
    conn.close()
